import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:ride_rex/constant.dart';
import 'package:ride_rex/service/log_service.dart';
import 'package:ride_rex/splash/splash_page.dart';
import 'package:ylm_ui_kit/ylm_ui_kit.dart';

import 'login/login_page.dart';
import 'main/main_page.dart';
import 'webview/web_page.dart';

class CommonRoute {
  ///获取入口
  static Widget getRoot(String token) {
    bool isFirstInstall = CommonStorage().getBool(StorageKey.spKeyFirstInstall, defaultValue: true);
    if (isFirstInstall) return const SplashPage();
    bool isLogin = token.notEmpty;
    return isLogin ? const MainPage() : const LoginPage();
  }

  ///关闭路由
  static close() => Get.back();

  ///打开登录
  static void openLogin() {
    _openRoot(const LoginPage());
  }

  ///打开首页
  static void openMain() {
    _openRoot(const MainPage());
  }

  /// 打开用户协议
  static void openProtocolPage() {
    open(
      const WebPage(
        url: ConstantValues.agreementUrl,
        title: 'Term of Use',
      ),
    );
    LMLogManager.stat(page: 'terms');
  }

  /// 打开隐私政策
  static void openPrivacyPage() {
    open(
      const WebPage(
        url: ConstantValues.privacyUrl,
        title: 'Privacy Policy',
      ),
    );
    LMLogManager.stat(page: 'privacy');
  }

  ///打开某个界面并关闭所有
  static void _openRoot<T>(T page) {
    Get.offAll(() => page);
  }

  static void open<T>(
    T page, {
    bool preventDuplicates = false,
    VoidCallback? back,
    Transition? transition,
    Duration? duration,
    bool fullscreenDialog = false,
  }) {
    Get.to(
      () => page,
      preventDuplicates: preventDuplicates,
      transition: transition,
      duration: duration,
      fullscreenDialog: fullscreenDialog,
    )?.whenComplete(() => back?.call());
  }

  static void offAll<T>(
    T page, {
    bool preventDuplicates = false,
    VoidCallback? back,
    Transition? transition,
    Duration? duration,
    bool fullscreenDialog = false,
  }) {
    Get.offAll(
      () => page,
      transition: transition,
      duration: duration,
      fullscreenDialog: fullscreenDialog,
    )?.whenComplete(() => back?.call());
  }

  static void until(
    String pageName, {
    bool preventDuplicates = false,
    VoidCallback? back,
    Transition? transition,
    Duration? duration,
    bool fullscreenDialog = false,
  }) {
    Get.until((route) => route.settings.name == pageName);
  }
}
